package com.demo.boot.commmon.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.aop.support.RegexpMethodPointcutAdvisor;
import org.springframework.cache.ehcache.EhCacheFactoryBean;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import com.demo.boot.commmon.aop.MethodCacheAfterAdvice;
import com.demo.boot.commmon.aop.MethodCacheInterceptor;


@Configuration
public class EhCacheConfig {

	@Bean
	public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
		EhCacheManagerFactoryBean fb = new EhCacheManagerFactoryBean();
		fb.setShared(true);
		fb.setCacheManagerName("cacheManager");
		fb.setConfigLocation(new ClassPathResource("ehcache.xml"));
		return fb;
	}
	
	@Bean
	public EhCacheFactoryBean ehCacheFactoryBean(EhCacheManagerFactoryBean ehCacheManagerFactoryBean){
		EhCacheFactoryBean eb = new EhCacheFactoryBean();
		eb.setCacheName("methodCache");
		eb.setCacheManager(ehCacheManagerFactoryBean.getObject());
		return eb;
	}
	
	@Bean
	public MethodCacheInterceptor methodCacheInterceptor(EhCacheFactoryBean efb){
		MethodCacheInterceptor mi = new MethodCacheInterceptor();
		mi.setCache(efb.getObject().getCacheManager().getCache("methodCache"));
		return mi;
	}
	
	@Bean
	public MethodCacheAfterAdvice methodCacheAfterAdvice(EhCacheFactoryBean efb){
		MethodCacheAfterAdvice ma = new MethodCacheAfterAdvice();
		ma.setCache(efb.getObject().getCacheManager().getCache("methodCache"));
		return ma;
	}
	
	
	@Bean
	public RegexpMethodPointcutAdvisor methodCacheDestory(MethodCacheAfterAdvice ma){
		RegexpMethodPointcutAdvisor ra = new RegexpMethodPointcutAdvisor();
		ra.setAdvice(ma);
		List<String> patterns = new ArrayList<String>();
		patterns.add("com.demo.boot.repositories.*.save*");
		patterns.add("com.demo.boot.repositories.*.delete*");
		patterns.add("org.springframework.data.repository.*.save*");
		patterns.add("org.springframework.data.repository.*.delete*");
		ra.setPatterns(patterns.toArray(new String[patterns.size()]));
		return ra;
	}
}
